package org.example.mq.common;

import java.io.*;

//进行系列化和反序列化的数据，必须实现Serializable接口
public class BinaryTool {
    /*
    * 将对象序列化为可变长字节数组(序列化-ByteArrayOutputStream)
    * */
    public static byte[] toBytes(Object object) throws IOException {
        try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){
            try(ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream)){
//                writeObject方法将数据序列化，写入outputStream中，因为outputStream与byteArrayOutputStream关联
//                最终写入byteArrayOutputStream
                outputStream.writeObject(object);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }


    /*
    * 反序列化（将字节数组变为对象）
    * */
    public static Object fromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
        Object object = null;
        try(ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)){
            try(ObjectInputStream objectInputStream =new ObjectInputStream(byteArrayInputStream)){
               object = objectInputStream.readObject();
            }
        }
        return object;
    }
}
